﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Open.Core.Extension;
using Open.Core.Extension.Results;
using Open.Core.Identity;
using Open.Domain.Abstractions;
using Open.Domain.Repositories.Extensions;
using Open.Product.Domain.Dto;
using Open.Product.Domain.Repositories;
using Open.Product.Domain.Service;

namespace Open.Product.Application.Service
{
    /// <summary>
    /// 商品服务实现类
    /// </summary>
    public class ProductService : IProductService
    {
        private IIdentityServer _context;
        private readonly IProductsRepository _repository;
        private readonly IProductStandardRepository _productStandardRepository;
        private readonly IProductStandardBarCodeRepository _productStandardBarCodeRepository;
        private readonly IUnitOfWork _unitOfWork;
        private readonly ILogger<ProductService> _logger;
        public ProductService(IIdentityServer context,
            IProductStandardRepository productStandardRepository,
            IProductStandardBarCodeRepository productStandardBarCodeRepository,
            IProductsRepository repository, IUnitOfWork unitOfWork)
        {
            _context = context;
            this._repository = repository;
            this._productStandardRepository = productStandardRepository;
            this._productStandardBarCodeRepository = productStandardBarCodeRepository;
            this._unitOfWork = unitOfWork;
        }

        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageResultDto<Domain.Model.Product>> GetListAsync(ProductGetListInput input)
        {

            var tenantId = await _context.GetTenancyName();
            var query = this._repository.GetQueryable()
                 .Where(c => c.TenantId == tenantId && c.IsWhether == false && c.Code != "kssy")
                 .OrderByDescending(c => c.IdentificationIndex)
                 .WhereIf(input.IdIndex != -1 && input.IdIndex > 0, c => c.IdentificationIndex >= input.IdIndex);

            var totalCount = query.Count();
            query = query.Skip((input.SkipCount - 1) * input.MaxResultCount).Take(input.MaxResultCount);
            var products = await query.ToListAsync();


            try
            {
                foreach (Domain.Model.Product item in products)
                {
                    //单位
                    var queryable = await this._productStandardRepository.GetQueryableAsync();
                    queryable = queryable.Where(c => c.TenantId == tenantId && c.ProductId == item.Id);
                    var standards = await queryable.ToListAsync();
                    item.BaseProductStandardList = standards;

                    foreach (var itemCode in item.BaseProductStandardList)
                    {
                        //规格条码
                        var codeQueryable = await this._productStandardBarCodeRepository.GetQueryableAsync();
                        codeQueryable = codeQueryable.Where(c => c.TenantId == tenantId && c.BaseProductStandardId == itemCode.Id);
                        var standardCode = await codeQueryable.ToListAsync();
                        itemCode.BaseProductStandardBarCodeList = standardCode;
                    }

                    ////品牌
                    //var brandData = await this._brandService.GetQueryAsync(new BaseBrandInput() { Id = item.BrandId });
                    //item.BrandName = brandData.Any() ? brandData[0].BrandName : "";
                    ////分类
                    //string name = string.Empty;
                    //var dataName = await recursiveCategory(item.ProductCategoryId, name);
                    //item.ProductCategoryName = dataName;
                }

            }
            catch (Exception e)
            {
                this._unitOfWork.Dispose();
                _logger.LogError(e.Message);
            }

            var result = new PageResultDto<Domain.Model.Product>();
            result.Item = products;
            result.Total = totalCount;

            return result;
        }


        /// <summary>
        /// 筛选
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> GetQueryAsync(ProductRequestInput input)
        {

            var result = new Domain.Model.Product();
            try
            {
                int tenantId = await _context.GetTenancyName();
                var query = await this._repository.GetQueryableAsync();
                query = query.Where(c => c.TenantId == tenantId && c.QId == 0 && c.Code != "kssy").OrderByDescending(c => c.IdentificationIndex)
                    .WhereIf(input.IdIndex != -1 && input.IdIndex > 0, c => c.IdentificationIndex == input.IdIndex)
                    .WhereIf(input.Id != 0, c => c.Id == input.Id)
                    .WhereIf(!string.IsNullOrEmpty(input.Name), c => c.Name == input.Name)
                    .WhereIf(!string.IsNullOrEmpty(input.Code), c => c.Code == input.Code);

                var products = await query.FirstOrDefaultAsync();
                if (products.Id > 0)
                {
                    result = products;
                    var queryable = await this._productStandardRepository.GetQueryableAsync();
                    queryable = queryable.Where(c => c.TenantId == tenantId && c.ProductId == products.Id);

                    //单位
                    var standards = await queryable.ToListAsync();
                    products.BaseProductStandardList = standards;
                }
                else
                {
                    return new Result(StateCode.Ok, "", null);
                }
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message);
            }

            return new Result(StateCode.Ok, "", result);
        }
    }
}
